package com.tools.hry.xls;


import com.tools.hry.xls.create.CreateResult;
import com.tools.hry.xls.create.DataSet;
import com.tools.hry.xls.create.IWriteCallbackFunction;
import com.tools.hry.xls.create.ParamBean;
import com.tools.hry.xls.create.util.CreateExcelUtils;
import com.tools.hry.xls.create.util.WriteExcelUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

/**
 *  JAVABEAN工具类 创建Excel
 * Created by 峥桂 on 2017/9/5
 */
public class CreateXlsTool {

    public static boolean createXLSFromIO(ParamBean paramBean, File file,
                                     IWriteCallbackFunction iCallbackFunction) throws Exception {
        FileOutputStream outputStream=new FileOutputStream(file);
        boolean flag= createXLS(paramBean,file.getName(),outputStream, iCallbackFunction);
        outputStream.flush();
        outputStream.close();
        return flag;

    }

    public static boolean createXLS(ParamBean paramBean,String  fileName, OutputStream outputStream,
                                    IWriteCallbackFunction iCallbackFunction) {
        CreateResult result=new CreateResult();
        boolean flag;
        try{
            DataSet set=null;
            //自定义headers时不通过反射类定义
            if(paramBean.getHeaders()!=null && paramBean.getHeaders().length>0
                    && paramBean.getDatalist()!=null && paramBean.getDatalist().size()>0){
                set=CreateExcelUtils.createXlsDataSet(paramBean.getHeaders(),
                        paramBean.getDatalist());
            }else{
                set=CreateExcelUtils.createXlsDataSet(paramBean.getDatalist());
            }
            set.setActionName(paramBean.getActionName());
            set.setTitleName(paramBean.getTitleName());
            set.setCreateTime(paramBean.getCreateTime());
            set.setSelfTemplatePath(paramBean.getSelfTemplatePath());
            set.setNeedTitle(paramBean.isNeedTitle());
            set.setNeedStyle(paramBean.isNeedStyle());
            if(outputStream!=null){
                WriteExcelUtils.writeExcelPOIToIo(set,fileName,outputStream);
            }

            if(iCallbackFunction!=null){
                iCallbackFunction.onSuccess(result);
            }
            flag=true;
        }catch (Exception e){
            if(iCallbackFunction!=null) {
                result.setException(e);
                iCallbackFunction.onFailure(result);
            }
            flag=false;
        }
        return flag;
    }

}
